﻿using System;
using System.ComponentModel;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using Microsoft.SilverlightMediaFramework.Data.Settings;
using SMF.HowTo.Data;
using SMF.HowTo.Shared.Eventing;
using SMF.HowTo.UI.ViewModels.Events;

namespace SMF.HowTo.UI.ViewModels
{
    public class MainViewModel : ViewModelBase
    {
        private SettingsDataClient _settingsClient;

        private bool _isSettingsLoaded = false;

        public MainViewModel()
        {
            EventAggregator.EventPublished += EventPublished;
        }

        private void EventPublished(Event evt)
        {
            if (evt is SettingsUrlRetrievedEvent)
            {
                string url = ((SettingsUrlRetrievedEvent) evt).Argument;
                LoadSettings(new Uri(url));
            }
        }

        private void LoadSettings(Uri settingsSource)
        {
            _settingsClient = new SettingsDataClient(settingsSource);
            _settingsClient.FetchFailed += (s, e) => NotifyUser(e.Result.Message);
            _settingsClient.FetchCompleted += (s, e) => OnSettingsLoaded(e.Result);
            _settingsClient.Fetch();
        }

        private void OnSettingsLoaded(SettingsBase settings)
        {
            if (!_isSettingsLoaded)
            {
                _isSettingsLoaded = true;
                var settingsLoadedEvent = new SettingsLoadedEvent(settings);
                EventAggregator.PublishEvent(settingsLoadedEvent);
            }
        }
    }
}